package com.ccl.iot.object;

import java.util.HashMap;

import com.ccl.iot.privates.ListMap;

public class IOTSyncObject implements IOTAbsSyncObject {
	public interface IOTSyncSource{
		public IOTSyncObjectInfo getSyncInfo();
	}
	
	private long iID;
	private String iSyncID = null;
	private IOTAbsSyncObject iInstance = this;
	private IOTSyncObjectCollector iCollector = null;
		
	public IOTSyncObject(){
		
	}
	
	public IOTSyncObject(IOTAbsSyncObject aInstance){
		if (aInstance != null){
			iInstance = aInstance;
		}
	}
	
	public IOTSyncObject(IOTSyncObjectCollector aCollector){
		setSyncCollector(aCollector);
	}
	
	public IOTSyncObject(IOTSyncObjectInfo aSyncInfo, IOTSyncObjectCollector aCollector){
		setSyncInfo(aSyncInfo, aCollector);
	}
	
	@Override
	public long getID() {
		return iID;
	}
	
	@Override
	public String getSyncInfoPrefix() {
		return KSYNC_INFO_PREFIX_BASE;
	}
	
	@Override
	public String getSyncID() {
		return iSyncID;
	}
	
	public void setSyncID(String aSyncID){
		iSyncID = aSyncID;
	}

	@Override
	public void setSyncCollector(IOTSyncObjectCollector aCollector) {
		iCollector = aCollector;
	}
	
	@Override
	public void setSyncInfo(IOTSyncObjectInfo aSyncInfo, IOTSyncObjectCollector aCollector){
		setSyncCollector(aCollector);
		
		if (aSyncInfo != null && aSyncInfo.isValid()){
			ListMap<String, Object> tInfos = aSyncInfo.getAllInfo();
			
			iID = aSyncInfo.getLongID();
			iSyncID = aSyncInfo.getID();
			
			if (tInfos != null){
				for (int i = 0, tCount = tInfos.size(); i < tCount; i++){
					String tKey = tInfos.getKeyAt(i);
					Object tObject = tInfos.getValueAt(i);
					
					if (tObject instanceof IOTSyncObjectInfo){
						if (aCollector != null){
							tObject = aCollector.findObject(((IOTSyncObjectInfo)tObject).getID());
						}else{
							tObject = null;
						}
					}
					
					if (tObject != null){
						iInstance.setParameter(tKey, tObject);
					}
				}
			}
		}
	}

	@Override
	public HashMap<String, Object> getSyncInfos() {
		return null;
	}

	@Override
	public Object[] getSyncObjects() {
		return null;
	}

	@Override
	public boolean setParameter(String aKey, Object aObject) {
		return false;
	}
	
	public void notifyBeforeObjectChange(){
		if (iCollector != null){
			iCollector.remove(iInstance);
		}
	}
	
	public void notifyObjectChange(){
		if (iCollector != null){
			iCollector.add(iInstance);
		}
	}
}
